package com.qianya;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGeneratorPlus {
    private static final String PACKAGE_NAME = "com.qianya.system.face.web";
    private static final String BASE_CONTROLLER_PACKAGE = "com.qianya.system.face.web";
    private static final String DATABASE_NAME = "192.168.0.202:3306/medic_smart_spills";
    private static final String DATABASE_USERNAME = "medical";
    private static final String DATABASE_PASSWORD = "root";
    private static final Boolean REMOVE_PREFIX = true; //是否去掉表前缀，如sys_user -》 User.java
    private static final Boolean MULTI_DIR = true; //是否多级文件夹，如果是 则如sys_user会创建sys/user/controller等文件夹
    private static final String PREFIX = null; //前缀
    private final static String author="lhl";
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        while(true){
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            final String projectPath = System.getProperty("user.dir")+ File.separator+"system-face";

            gc.setOutputDir(projectPath + "/src/main/java");
            gc.setAuthor(author);
            gc.setDateType(DateType.ONLY_DATE);
            gc.setOpen(false);
            gc.setFileOverride(true);// 是否覆盖文件
            gc.setBaseResultMap(true);// XML ResultMap
            gc.setBaseColumnList(true);// XML columList
            gc.setSwagger2(true); //实体属性 Swagger2 注解
            gc.setIdType(IdType.UUID); //id类型UUID
            mpg.setGlobalConfig(gc);

            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://" + DATABASE_NAME + "?useUnicode=true&useSSL=false&characterEncoding=utf8");
            // dsc.setSchemaName("public");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername(DATABASE_USERNAME);
            dsc.setPassword(DATABASE_PASSWORD);
            mpg.setDataSource(dsc);

            // 包配置
            final PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("模块名"));
            final String modelPath = System.getProperty("user.dir")+ File.separator+"model"+"/src/main/java/com/qianya/model/pojo/"+pc.getModuleName();
            pc.setParent(PACKAGE_NAME + (PREFIX != null ? "." + PREFIX : ""));
            pc.setController("controller");
            pc.setEntity("model");
            pc.setMapper("mapper");
            mpg.setPackageInfo(pc);
            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };
            // 如果模板引擎是 freemarker
            String templatePath = "/templates/mapper.xml.ftl";
            // 如果模板引擎是 velocity
            // String templatePath = "/templates/mappwechat_responseer.xml.vm";

            // 自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                    return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();
            // 配置自定义输出模板
            //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
           // String thisPath = "D:/workspace/samrt-pills/util/src/main/java/codes";
           // templateConfig.setEntity("/templates/entity.java");
            // templateConfig.setService();
            templateConfig.setController("/templates/controller.java");
            templateConfig.setService("/templates/service.java");
            templateConfig.setServiceImpl("/templates/serviceImp.java");
            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);
            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
            // 公共父类
            strategy.setSuperControllerClass(BASE_CONTROLLER_PACKAGE + ".BaseController");
            // 写于父类中的公共字段
            //strategy.setSuperEntityColumns("id");
            strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            if (REMOVE_PREFIX) {
                if(MULTI_DIR){
                    strategy.setTablePrefix(PREFIX + "_");
                }else {
                    strategy.setTablePrefix(pc.getModuleName() + "_");
                }
            }
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            File fileVO=new File(modelPath+File.separator+"vo");
            File fileQO=new File(modelPath+File.separator+"qo");
            if (!fileVO.exists()){
                fileVO.mkdirs();
            }
            if (!fileQO.exists()){
                fileQO.mkdirs();
            }
             mpg.execute();
        }
    }

}
